package xmltomce;

import java.io.IOException;

import org.xml.sax.SAXException;

import javax.xml.parsers.*;
import javax.xml.xpath.*;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.namespace.QName;



public class XPath {
	private Document doc = null;
	private DocumentBuilderFactory dbFactory = null;
	private DocumentBuilder builder = null;
	private XPathFactory xpFactory = null;
	private javax.xml.xpath.XPath xpath = null;
	
	
	public XPath(String xmlFilePath){
		initDocumentBuilder();
		try {
			doc = builder.parse(xmlFilePath);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		initXPath();
	}
	
	public XPath(Node xmlNode){
		initDocumentBuilder();
		doc = builder.newDocument();
		doc.adoptNode(xmlNode);
		doc.appendChild(xmlNode);
		initXPath();
	}
	
	private void initDocumentBuilder(){
		dbFactory = DocumentBuilderFactory.newInstance();
		dbFactory.setNamespaceAware(true); // never forget this!
		try {
			builder = dbFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	private void initXPath(){
		xpFactory = XPathFactory.newInstance();
		xpath = xpFactory.newXPath();
	}
	
	public Node getNode(String query){
		Node node = null;
		Object result = getQueryResult(query, XPathConstants.NODE);
		if (result instanceof Node){
			node = (Node) result;
		}
		return node;
	}
	
	public NodeList getNodeList(String query){
		NodeList nodeList = null;
		Object result = getQueryResult(query, XPathConstants.NODESET);
		if (result instanceof NodeList){
			nodeList = (NodeList) result;
		}
		return nodeList;
	}
	
	public String getNodeListAsText(String query, char valueSeperator){
		String text = "";
		NodeList nodeList = getNodeList(query);
		for (int i = 0; i<nodeList.getLength(); i++){
			Node node = nodeList.item(i);
			if (!text.isEmpty()){
				text += valueSeperator+" ";
			}
			text += node.getTextContent();
		}
		return text;
	}
	
	public String getNodeText(String query){
		String text = "";
		Object result = getQueryResult(query, XPathConstants.STRING);
		if (result instanceof String){
			text = (String) result;
		}
		return text;
	}
	
	public int getNodeIntValue(String query){
		int intValue = 0;
		Object result = getQueryResult(query, XPathConstants.NUMBER);
		if (result instanceof Number){
			intValue = ((Number)result).intValue();
		}
		return intValue;
	}
	
	private Object getQueryResult(String query, QName xpathConst){
		Object result = null;
		try{
			XPathExpression expr = xpath.compile(query);
			result = expr.evaluate(doc, xpathConst);
		}catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return result;
	}

}
